package cn.ultrarisk.scadmin.manager.web.controller.script;

import cn.ultrarisk.scadmin.manager.biz.context.RequestContext;
import cn.ultrarisk.scadmin.manager.biz.user.entity.Admin;
import cn.ultrarisk.scadmin.manager.util.IOUtil;
import cn.ultrarisk.scadmin.manager.web.controller.BaseController;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.StringReader;

/**
 * ScriptController
 *
 * @author sevendlong(lin23871@163.com)
 * @date 2014/6/27
 * @since V1.0
 */
@Controller
@RequestMapping("/script/")
public class ScriptController extends BaseController {
    @Autowired
    private DruidDataSource dataSource;

    @ResponseBody
    @RequestMapping(value = "{resource}", method = RequestMethod.GET)
    public ResponseEntity<String> runSql(@PathVariable("resource") String resource) throws Exception {
        Admin admin = RequestContext.getAdmin();
        if (Admin.ROOT_ACCOUNT.equals(admin.getAccount())) {
            ScriptRunner runner = new ScriptRunner(dataSource.getConnection());
            runner.setAutoCommit(true);
            runner.setStopOnError(true);

            String sql = IOUtil.in2Str(ScriptController.class.getResourceAsStream("/com/cyou/fz/search/admin/web/controller/script/" + resource + ".sql"), "utf-8");
            StringReader reader = new StringReader(sql);
            runner.runScript(reader);
            reader.close();
            return getOkResponseEntity("success");
        }
        return getOkResponseEntity("no authentication");
    }
}
